/**
 * 
 */
package pl.net.beercrm.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import pl.net.beercrm.dao.GenericDao;
import pl.net.beercrm.model.Customer;

/**
 * @author Rafi
 * 
 */
@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class CustomerService implements GenericService<Customer, Long> {

	@Autowired
	private GenericDao<Customer, Long> customerDao;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#upsert(java.lang.Object)
	 */
	@Override
	public void upsert(Customer object) {
		List<Customer> objectList = findByGuid(object.getCustomerId());
		if(objectList.size() > 0) {
			Customer persistedObject = objectList.get(0);
			persistedObject.setName(object.getName());
			persistedObject.setSurname(object.getSurname());
			persistedObject.setBirthDate(object.getBirthDate());
			persistedObject.setRegon(object.getRegon());
			persistedObject.setPesel(object.getPesel());
			persistedObject.setNip(object.getNip());
			persistedObject.setCompanyName(object.getCompanyName());
			persistedObject.setPostalCode(object.getPostalCode());
			persistedObject.setStreet(object.getStreet());
			persistedObject.setCity(object.getCity());
			persistedObject.setState(object.getState());
			persistedObject.setPhone(object.getPhone());
			persistedObject.setEmail(object.getEmail());
			customerDao.update(persistedObject);
		} else {
			customerDao.create(object);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#delete(java.lang.Object)
	 */
	@Override
	public void delete(Customer object) {
		List<Customer> persistedObjects = findByGuid(object.getCustomerId());
		for(Customer customer : persistedObjects) {
			customerDao.delete(customer);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#find(java.io.Serializable)
	 */
	@Override
	public Customer find(Long id) {
		return customerDao.findById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#list()
	 */
	@Override
	public List<Customer> list() {
		return customerDao.findAll();
	}

	/* (non-Javadoc)
	 * @see pl.net.beercrm.service.GenericService#findByGuid(java.lang.String)
	 */
	@Override
	public List<Customer> findByGuid(String guid) {
		return customerDao.findAllByProperty("customerId", guid);
	}

	/* (non-Javadoc)
	 * @see pl.net.beercrm.service.GenericService#findByProperty(java.lang.String, java.lang.Object)
	 */
	@Override
	public List<Customer> findByProperty(String property, Object value) {
		return customerDao.findAllByProperty(property, value);
	}

}
